#!/usr/bin/python
#Developed by Florin Nicusor Coada for 216 CR
#Based on the udp_chat_client2.py tutorial from professor Christopher Peters
from Tkinter import *
import socket,select
from login import *
import sys

HOST = '192.168.1.2' #Server
OPORT = 50007    # The same port as used by the server
IPORT=50008 #Listening port
out_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
in_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
in_socket.bind(('', IPORT))
user=log()
out_socket.sendto("user:%s"%user,(HOST,OPORT))



##GUI interface

class MyMenu:
    def __init__(self,parent):
        self.mainframe=Frame(parent)
        frame=Frame(self.mainframe)
        frame.grid(row=0,column=0)
        self.user=user
        ##Area above chat
        self.titleLabel=Label(frame,text="Battle Botz",bg="LightGoldenrod2",font=("Helvetica",24))
        self.titleLabel.grid(row=1,column=0,columnspan=5,sticky=NSEW)
        self.meLabel=Label(frame,text="by Florin N. Coada",bg="LightGoldenrod2")
        self.meLabel.grid(row=1,column=5,columnspan=2,sticky=NSEW)
        self.createButton=Button(frame,text="Create")
        self.createButton.grid(column=2,row=2,sticky=NSEW)
        self.joinButton=Button(frame,text="Join",width=5)
        self.joinButton.grid(column=3,columnspan=2,row=2,sticky=NSEW)
        self.arangeLabel=Label(frame,width=50)
        self.arangeLabel.grid(row=2,column=0,columnspan=2)

        ##Chat related area
        self.textArea=Listbox(frame)
        self.typeArea=Entry(frame)
        self.sendButton=Button(frame,text="Send",command=self.addToChat,background = 'LightGoldenrod2')
        self.users=Label(frame,text="Users:",background = 'LightGoldenrod')
        self.userList=Listbox(frame,width=20)
        self.scrollbar=Scrollbar(frame)
        self.option=Button(frame,text="Options",command=self.newDetails)
        self.exit=Button(frame,text="Exit",command=self.exitChat)
        self.textArea.grid(column=0,columnspan=4,row=3,rowspan=2,sticky=NSEW)
        self.typeArea.grid(column=0,columnspan=3,row=5,rowspan=2,sticky=NSEW)
        self.sendButton.grid(column=3,columnspan=2,row=5,sticky=NSEW)
        self.userList.grid(column=5,row=4,columnspan=2,sticky=NSEW)
        self.users.grid(column=5,row=2,rowspan=2,columnspan=2,sticky=NSEW)
        self.scrollbar.grid(column=4,row=3,rowspan=2,sticky=NSEW)
        self.option.grid(column=5,row=5,sticky=NSEW)
        self.exit.grid(column=6,row=5,sticky=NSEW)
        self.scrollbar.configure(command=self.textArea.yview)
        self.kickState=0;
## set up the main window
        self.mainframe.grid()
## set the title
        self.mainframe.master.title("Chat box")
    
    def addToChat(self,*ignore):
        message=self.typeArea.get()
        if(self.kickState==0 and self.checkMsg(message)==1):
            out_socket.sendto(message,(HOST,OPORT))
        elif (self.kickState==1):
            self.textArea.insert(END,"You have been kicked")
            self.textArea.yview(END)
        elif (self.kickState==2):
            self.textArea.insert(END,"You have been banned")
            self.textArea.yview(END)
        if self.typeArea.get()=="quit":
            self.exitChat()
        self.typeArea.delete(0,END)


    def updateChat(self):
        rlist,wlist,elist=select.select([in_socket],[],[],1)
        if len(rlist)!=0:
            data=in_socket.recv(1024)
            if len(data)!=0 and data.startswith("ulist:")==False:
                self.textArea.insert(END,data)                
                if data.startswith("From"):
                    self.textArea.itemconfig(END,fg="DarkSeaGreen")
                if (data=="You have been kicked"):
                    self.kickState=1;
                elif (data=="You have been banned"):
                    self.kickState=2;
        self.textArea.yview(END)
        if(self.kickState==0):
            self.userUpdate()
        main_win.after(1000,self.updateChat)

    def userUpdate(self):
        out_socket.sendto("/update",(HOST,OPORT))
        k=in_socket.recv(1024)
        self.userList.delete(0,END)
        tag="Admin"
        if (k.startswith("ulist:")):
            k=k[k.find(":")+1:]
            while k!="":
                    k=k[k.find(" ")+1:]
                    user=k[:k.find(" ")]
                    if k!="":
                        if(userType(user)==1):
                            tag="Admin"
                        else:
                            tag="User"
                        self.userList.insert(END,user+" - "+tag)
                        if (tag=="Admin"):
                            self.userList.itemconfig(END,fg="RED")
                
    def newDetails(self):
        data=details(self.user)
        if data[1]!="":
            out_socket.sendto("user:"+data[1],(HOST,OPORT))
            self.user=data[1]

    def exitChat(self):
        out_socket.sendto("{0} has left".format(self.user),(HOST,OPORT))
        out_socket.sendto("/kick -{0}".format(self.user),(HOST,OPORT))
        sys.exit()

    def checkMsg(self,message):
        if message=="":
            return 0
        elif message.startswith("/kick"):
            if(userType(self.user)==1):
                return 1
            else:
                self.textArea.insert(END,"You are not an admin!")
                return 0
        elif message.startswith("/ban"):
            if(userType(self.user)==1):
                name=message[message.find("-")+1:]
                banUser(name)
                return 1
            else:
                self.textArea.insert(END,"You are not an admin!")
                return 0
        elif message.startswith("user:"):
            name=message[message.find(":")+1:]
            if(newName(self.user,name)==1):
                out_socket.sendto(message,(HOST,OPORT))
                self.user=name
                return 1
            else :
                self.textArea.insert(END,"Name already taken")
                return 0
        return 1

##new tkinter root
main_win=Tk()
app = MyMenu(main_win)
main_win.bind('<Return>',app.addToChat)
main_win.after(1000,app.updateChat)
main_win.mainloop()

#Close the socket
out_socket.close()
in_socket.close()

